import express, { Request, Response } from 'express';
import cors from 'cors';
import path from 'path';
import { Lists, Content } from './types/types';

const app = express();
app.use(cors());
app.use(express.json());

async function start(): Promise<void> {
  try {
    // API 路由
    app.get('/api/lists', (_req: Request, res: Response) => {
      const lists: Lists = {
        left: [
          { id: 1, name: 'Left Item 1222' },
          { id: 2, name: 'Left Item 2' },
        ],
        right: [
          { id: 1, name: 'Right Item 1' },
          { id: 2, name: 'Right Item 2' },
        ],
      };
      res.json(lists);
    });

    app.get('/api/content', (_req: Request, res: Response) => {
      const content: Content = {
        title: 'Welcome to My Website',
        body: 'Here is the main content of the page2323.',
        footer: 'Footer text here.',
      };
      res.json(content);
    });

    // 将 .output/public 目录作为静态文件服务
    app.use(express.static(path.join(__dirname, '.output/public')));

    // 处理所有其他路由
    app.all('*', async (_req: Request, res: Response) => {
      try {
        console.log('666');
      } catch (err) {
        console.error('Error handling request:', err);
        res.status(500).send('Internal Server Error');
      }
    });

    // 启动服务
    const PORT: number = 3001;
    app.listen(PORT, () => {
      console.log(`Backend is running on http://localhost:${PORT}`);
      console.log('API endpoints:');
      console.log(`- http://localhost:${PORT}/api/lists`);
      console.log(`- http://localhost:${PORT}/api/content`);
      startSSR();
    });
  } catch (err) {
    console.error('Error starting server:', err);
    process.exit(1);
  }
}

// 启动SSR
async function startSSR(): Promise<void> {
  try {
    const { default: handler } = await import('./.output/server/index.mjs');
    console.log('handler', handler);
    if (typeof handler === 'function') {
      await handler();
    }
    console.log('启动SSR');
  } catch (err) {
    console.error('Error starting SSR:', err);
  }
}

// 启动应用
start().catch((err: Error) => {
  console.error('Unhandled error:', err);
  process.exit(1);
}); 